<template>
<form class="form-horizontal" role="form" @submit.prevent="submitAdmin" autocomplete="off">
  <div class="modal fade" :id="modalId" tabindex="-1" role="dialog" :aria-labelledby="'modal-'+ modalId +'-lable'" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" :id="'modal-'+ modalId +'-lable'">{{editAdmin.roleId ? "编辑":"新增"}}账号</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group" v-show="!initAdmin.platforms">
            <label class="control-label">平台类型：</label>
            <div style="display:inline-block">
              <select class="selectpicker" multiple="multiple" title="-平台类型-" data-actions-box="true" @change="setPlatforms">
                <option v-for="(plat, index) in platforms" :key="index" :value="index">{{plat.text}}</option>
              </select>
              <p class="invalid-feeback" v-if="$v.editAdmin.platforms.$error && !$v.editAdmin.platforms.required">请选择平台类型.</p>
            </div>
          </div>
          <div class="form-group">
            <label class="control-label">账号名称：</label>
            <div style="display:inline-block">
              <input type="text" v-model.trim="editAdmin.name" @input="delayTouch($v.editAdmin.name)" class="form-control"
                :disabled="initAdmin.adminId">
              <p class="invalid-feeback" v-if="$v.editAdmin.name.$error && !$v.editAdmin.name.required">账号名称不能为空.</p>
              <p class="invalid-feeback" v-if="$v.editAdmin.name.$error && !$v.editAdmin.name.existsName">账号名称已存在.</p>
            </div>
          </div>
          <div class="form-group">
            <label class="control-label">手机号：</label>
            <div style="display:inline-block">
              <input type="text" v-model.trim="editAdmin.mobile" @input="delayTouch($v.editAdmin.mobile)" class="form-control">
              <p class="invalid-feeback" v-if="$v.editAdmin.mobile.$error && !$v.editAdmin.mobile.required">手机号不能为空.</p>
              <p class="invalid-feeback" v-if="$v.editAdmin.mobile.$error && !$v.editAdmin.mobile.existsMobile">手机号已存在.</p>
            </div>
          </div>
          <div class="form-group">
            <label class="control-label">密码：</label>
            <div style="display:inline-block">
              <input type="text" v-model.trim="editAdmin.pwd" class="form-control">
              <p class="invalid-feeback" v-if="$v.editAdmin.pwd.$error && !$v.editAdmin.pwd.required">密码不能为空.</p>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取 消</button>
          <button type="submit" class="btn btn-primary">提 交</button>
        </div>
      </div>
    </div>
  </div>
</form>
</template>
<script>
  import $ from 'jquery'
  import cfg from '../dist/js/config'
  import { required } from 'vuelidate/lib/validators'
  import { platforms } from '../dist/js/enum'

  const modalId = 'modal-edit-admin-' + new Date().getTime()
  const initAdmin = {}
  const editAdmin = {}

  var $platform = null;

  function modal(isShow) {
    $(() => {
      $('#' + this.modalId).modal(isShow ? 'show' : 'hide')
    })
  }
  function open() {
    this.modal(true)
  }
  function hide() {
    this.modal(false)
  }
  function response(admin) {
    this.$emit('admin', admin)
    this.modal(false)
  }

  const touchMap = new WeakMap()

  const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ^%@#!$";

  function pwd() {
    let pwd = "";
    for (let i = 0; i < 6; i++) {
      pwd += chars.charAt(parseInt(Math.random() * chars.length - 1));
    }
    return pwd;
  }

  function delayTouch($v) {
    $v.$reset()
    if (touchMap.has($v)) {
      clearTimeout(touchMap.get($v))
    }
    touchMap.set($v, setTimeout($v.$touch, 500))
  }

  function setAdmin(admin) {
    this.initAdmin = Object.assign({}, admin)
    this.editAdmin = Object.assign({}, admin)
    if ($platform && admin.platforms) {
      let plats = []
      for (let i in platforms) {
        if ((admin.platforms & (1 << i)) > 0) {
          plats.push(i)
        }
      }
      $platform.selectpicker('val', plats)
    } else if ($platform) {
      $platform.selectpicker('val', '')
    }
    if (!this.editAdmin.adminId) {
      this.$set(this.editAdmin, 'sex', 0)
      this.$set(this.editAdmin, 'pwd', pwd())
    }
  }
  function setPlatforms(event) {
    $platform = $(event.target)
    const plats = $platform.val();
    let platforms = 0;
    if (plats.length > 0) {
      for (let i in plats) {
        platforms |= (1 << parseInt(plats[i]));
      }
    }
    this.$set(this.editAdmin, 'platforms', platforms)
  }
  function submitAdmin(event) {
    this.$v.$touch()
    if (this.$v.$invalid) return
    const $target = $(event.target)
    if (!$target.lock()) return
    $.ajax({
      contentType: 'application/json; charset=UTF-8',
      url: cfg.serverPath + '/admin/' + (this.editAdmin.adminId ? 'edit' : 'add') + this.action(),
      type: this.editAdmin.adminId ? 'patch' : 'put',
      data: JSON.stringify(this.editAdmin),
      error: () => {
        $target.unlock()
      },
      success: result => {
        if (result.status != 0) {
          $target.failMsg(result.message)
          return;
        }
        $target.unlock()
        if (this.initAdmin.adminId) {
          this.response(this.editAdmin)
          return
        }
        // 获取新账号的完整信息
        $.get(cfg.serverPath + "/admin/page" + this.action(),
          {
            adminId: result.data
          },
          result => {
            if (result.status != 0) {
              $target.failMsg(result.message)
              return
            }
            this.response(result.data.list[0])
          })
      }
    });
  }
  function existsName(name) {
    if (!name) return true
    return new Promise((resolve) => {
      const search = {
        name: name,
        pageSize: 1
      }
      $.get(cfg.serverPath + '/admin/page' + this.action(),
        search,
        result => {
          if (result.status != 0) {
            $(document).failMsg(result.message)
            resolve(false)
            return
          }
          if (result.data.list) {
            resolve(false)
            return
          }
          resolve(true)
        })
    })
  }
  function existsMobile(mobile) {
    if (!mobile || (this.initAdmin && this.initAdmin.mobile == mobile)) return true
    return new Promise((resolve) => {
      const search = {
        mobile: mobile,
        pageSize: 1
      }
      $.get(cfg.serverPath + '/admin/page' + this.action(),
        search,
        result => {
          if (result.status != 0) {
            $(document).failMsg(result.message)
            resolve(false)
            return
          }
          if (result.data.list) {
            resolve(false)
            return
          }
          resolve(true)
        })
    })
  }
  function action() {
    return '/!/' + this.platType + '-' + (this.editAdmin.adminId ? 'edit' : 'add') + '-admin'
  }
  export default {
    props: {
      platType: String
    },
    data() {
      return {
        modalId,
        platforms,
        editAdmin,
        initAdmin,
      }
    },
    methods: {
      open,
      hide,
      response,
      modal,
      delayTouch,
      setAdmin,
      setPlatforms,
      submitAdmin,
      action
    },
    created() {
      $(function() {
        $(".selectpicker").selectpicker();
      });
    },
    validations() {
      if (this.initAdmin.adminId) {
        return {
          editAdmin: {
            platforms: {
            },
            name: {
            },
            pwd: {
            },
            mobile: {
              required,
              existsMobile
            }
          }
        }
      } else {
        return {
          editAdmin: {
            platforms: {
              required
            },
            name: {
              required,
              existsName
            },
            mobile: {
              required,
              existsMobile
            },
            pwd: {
              required
            }
          }
        }
      }

    }
  }
</script>